package com.ali.config;

import com.ali.common.BeanName;
import com.ali.common.MethodName;
import spring.annotation.MyComponent;
import spring.service.MyBeanPostProcessor;

import java.lang.reflect.Proxy;
import java.util.Objects;

@MyComponent(BeanName.MY_BEAN_POST_PROCESSOR_IMPL)
public class MyBeanPostProcessorImpl implements MyBeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (Objects.equals(BeanName.USER_SERVICE_IMPL, beanName)) {
            System.out.println(BeanName.USER_SERVICE_IMPL + "初始化前操作");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (Objects.equals(BeanName.USER_SERVICE_IMPL, beanName)) {
            System.out.println(BeanName.USER_SERVICE_IMPL + "初始化后操作");
        }
        return bean;
    }

    @Override
    public Object aopProcess(Object bean, String beanName) {
        if (Objects.equals(BeanName.USER_SERVICE_IMPL, beanName)) {
            //获取类加载器
            ClassLoader classLoader = MyBeanPostProcessorImpl.class.getClassLoader();
            Class<?>[] beanClass = bean.getClass().getInterfaces();
            //获取代理对象
            return Proxy.newProxyInstance(classLoader, beanClass, (proxy, method, args) -> {
                if (Objects.equals(MethodName.USER_SERVICE_TEST, method.getName())) {
                    System.out.println("AOP处理，执行" + MethodName.USER_SERVICE_TEST + "方法之前");
                    Object object = method.invoke(bean, args);
                    System.out.println("AOP处理，执行" + MethodName.USER_SERVICE_TEST + "方法之后");
                    return object;
                }

                return method.invoke(bean, args);
            });
        }
        return bean;
    }
}
